<template>
  <div class="payment-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="支付流水号">
          <el-input v-model="queryParams.paymentNo" placeholder="请输入支付流水号" clearable />
        </el-form-item>
        <el-form-item label="订单编号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="queryParams.payType" placeholder="请选择支付方式" clearable>
            <el-option label="微信支付" value="WECHAT" />
            <el-option label="支付宝" value="ALIPAY" />
          </el-select>
        </el-form-item>
        <el-form-item label="支付状态">
          <el-select v-model="queryParams.status" placeholder="请选择支付状态" clearable>
            <el-option label="待支付" value="PENDING" />
            <el-option label="支付成功" value="SUCCESS" />
            <el-option label="支付失败" value="FAILED" />
            <el-option label="已关闭" value="CLOSED" />
            <el-option label="已退款" value="REFUNDED" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计数据 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-title">支付总笔数</div>
          <div class="stats-value">{{ stats.totalCount || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-title">支付总金额</div>
          <div class="stats-value">¥{{ stats.totalAmount || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-title">退款笔数</div>
          <div class="stats-value">{{ stats.refundCount || 0 }}</div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-title">退款金额</div>
          <div class="stats-value">¥{{ stats.refundAmount || 0 }}</div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="paymentList">
      <el-table-column label="支付流水号" prop="paymentNo" />
      <el-table-column label="订单编号" prop="orderNo" />
      <el-table-column label="支付金额" prop="amount">
        <template #default="{ row }">
          ¥{{ row.amount }}
        </template>
      </el-table-column>
      <el-table-column label="支付方式" prop="payType">
        <template #default="{ row }">
          {{ row.payType === 'WECHAT' ? '微信支付' : '支付宝' }}
        </template>
      </el-table-column>
      <el-table-column label="支付状态" prop="status">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" prop="payTime" />
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button
            v-if="row.status === 'SUCCESS'"
            type="warning"
            size="small"
            @click="handleRefund(row)"
          >
            申请退款
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleDetail(row)"
          >
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model="currentPage"
        :page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getPaymentList, getPaymentStats, refundPayment } from '@/api/payment'
import { ElMessage, ElMessageBox } from 'element-plus'

const loading = ref(false)
const paymentList = ref([])
const total = ref(0)
const stats = ref({})
const dateRange = ref([])
const currentPage = ref(1)
const pageSize = ref(10)

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  paymentNo: '',
  orderNo: '',
  payType: '',
  status: '',
  startTime: '',
  endTime: ''
})

// 获取支付记录列表
const getList = async () => {
  loading.value = true
  try {
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.value.startTime = dateRange.value[0]
      queryParams.value.endTime = dateRange.value[1]
    }
    const res = await getPaymentList(queryParams.value)
    paymentList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取支付记录列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStats = async () => {
  try {
    const res = await getPaymentStats(queryParams.value)
    stats.value = res.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
  getStats()
}

// 重置
const resetQuery = () => {
  dateRange.value = []
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    paymentNo: '',
    orderNo: '',
    payType: '',
    status: '',
    startTime: '',
    endTime: ''
  }
  handleQuery()
}

// 分页
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 申请退款
const handleRefund = (row) => {
  ElMessageBox.confirm('确认要对此支付记录申请退款吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await refundPayment(row.id)
      ElMessage.success('退款申请提交成功')
      getList()
    } catch (error) {
      console.error('退款申请失败:', error)
    }
  })
}

// 查看详情
const handleDetail = (row) => {
  // TODO: 实现查看详情功能
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    PENDING: 'warning',
    SUCCESS: 'success',
    FAILED: 'danger',
    CLOSED: 'info',
    REFUNDED: 'info'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    PENDING: '待支付',
    SUCCESS: '支付成功',
    FAILED: '支付失败',
    CLOSED: '已关闭',
    REFUNDED: '已退款'
  }
  return texts[status] || status
}

onMounted(() => {
  getList()
  getStats()
})
</script>

<style scoped>
.payment-container {
  padding: 20px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.stats-title {
  font-size: 14px;
  color: #666;
}

.stats-value {
  font-size: 24px;
  color: #409EFF;
  margin-top: 10px;
}

.search-bar {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
}

.form-inline {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 